import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
import type { loginFormData, loginResponseData, userResponseData } from '@/api/user/type'
import type { UserState } from './types/types'
import { setToken, getToken, removeToken } from '@/utils/auth'
import { constantRoute } from '@/router/routes'

const useUserStore = defineStore('user', {
  state: (): UserState => {
    return {
      // 保证pinia中的token是持久化的
      token: getToken(),
      menuRoutes: constantRoute,
      avatar: '',
      username: '',
    }
  },
  actions: {
    async userLogin(loginForm: loginFormData) {
      const res: loginResponseData = await reqLogin(loginForm)
      if (res.code === 200) {
        this.token = res.data
        setToken(this.token)
        return 'ok'
      } else {
        return Promise.reject(new Error(res.data))
      }
    },
    async userInfo() {
      const res: userResponseData = await reqUserInfo()
      if (res.code === 200) {
        this.avatar = res.data.avatar
        this.username = res.data.name
        localStorage.setItem('curUserName', this.username)
      } else {
        return Promise.reject(new Error(res.message))
      }
    },
    async useLogout() {
      const res: any = await reqLogout()
      if (res.code === 200) {
        this.token = ''
        this.username = ''
        this.avatar = ''
        this.menuRoutes = []
        removeToken()
        return 'ok'
      } else {
        return Promise.reject(new Error(res.message))
      }
    },
  },
  getters: {},
})

export default useUserStore
